package com.dong.YOLOAPI.aiAPI;
import com.dong.YOLOAPI.imagesrecognize2;
import com.dong.YOLOAPI.imagesrecognize3;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import com.dong.YOLOAPI.imagesrecognize1;

import java.util.Base64;
import java.util.List;

// 响应数据模型
@Data
class InferenceResponse {
    private List<InferenceResult> inference_results;
    private String processed_image;


}

// 推理结果项模型
@Data
class InferenceResult {
    private int class_num;  // 使用class_num避免与关键字冲突
    private double confidence;
    private String label;


}

// 请求体模型
@Data
class InferenceRequest {
    private String image;

    public InferenceRequest(String image) {
        this.image = image;
    }

}

// 接口调用服务类
@Component
public class ImageInferenceService {
    private final WebClient webClient;
@Resource
    imagesrecognize1 imagesrecognizeONE;
    @Resource
    imagesrecognize2 imagesrecognizeTWO;
    @Resource
    imagesrecognize3 imagesrecognizeTHREE;
    // 初始化WebClient
    public ImageInferenceService() {
        this.webClient = WebClient.builder()
                .baseUrl("http://127.0.0.1:6000")
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .build();
    }

    /**
     * 发送图像识别请求
     * @param base64Image 以data:image/png;base64,开头的Base64编码图片
     * @return 包含推理结果的响应对象Mono
     */

    public Mono<InferenceResponse> inferImage(String base64Image) {
        // 创建请求体对象
        InferenceRequest request = new InferenceRequest(base64Image);

        // 发送POST请求并处理响应
        return webClient.post()
                .uri("/infer")
                .body(Mono.just(request), InferenceRequest.class)
                .retrieve()
                // 处理成功响应
                .bodyToMono(InferenceResponse.class)
                // 处理错误响应
                .doOnError(error -> System.err.println("接口调用失败: " + error.getMessage()));
    }

    // 使用示例
    @Async("taskExecutor")
    public void   pullFromYOLOapiOne(String base64Image, String zoneid) {
        ImageInferenceService service = new ImageInferenceService();
        // 替换为实际的Base64图片数据
//        String base64Image ;

        // 调用接口并处理结果
        service.inferImage(base64Image)
                .subscribe(response -> {
                    // 处理推理结果
                    System.out.println("===== 推理结果 =====");
                    for (InferenceResult result : response.getInference_results()) {
                        System.out.printf("类别: %s (编号: %d), 置信度: %.2f%n",
                                result.getLabel(),
                                result.getClass_num(),
                                result.getConfidence());
                    }

                    // 处理返回的处理后图片
                    //推送到页面
//                    .length());
                    String pureBase64 = response.getProcessed_image().replaceAll("^data:image/[^;]+;base64,", "");
                    if(zoneid.equals("one")) {
                        imagesrecognizeONE.broadcastFrame( Base64.getDecoder().decode(pureBase64));

                    } else if (zoneid.equals("two")) {
                        imagesrecognizeTWO.broadcastFrame( Base64.getDecoder().decode(pureBase64));

                    } else if (zoneid.equals("three")) {
                        imagesrecognizeTHREE.broadcastFrame( Base64.getDecoder().decode(pureBase64));

                    }


                    System.out.println("\n===== 处理后图片信息 =====");
                    System.out.println("处理后图片Base64长度: " + response.getProcessed_image().length());
                    // 此处可添加Base64解码保存图片的逻辑
                });

        // 等待异步操作完成
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();

        }

    }
}